<template>
  <div class="chart-container">
    <div v-if="data.length > 0" ref="chartRef" class="chart-content"></div>
    <chartEmpty v-else />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import * as echarts from "echarts";
import chartEmpty from "./chartEmpty.vue";

const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
});

const chartRef = ref(null);
let chart = null;

function getColor(type) {
  console.log("getColor: ", type);
  if (type === "completed") {
    return "#04CCA4";
  }
  if (type === "uncompleted") {
    return "#FF6B3B";
  }
  if (type === "unknown" || type === "undetermined") {
    return "#a8a8a8";
  }
  return `#${Math.floor(Math.random() * 16777215)
    .toString(16)
    .padStart(6, "0")}`;
}

function updateChart() {
  if (!chart) return;

  const total = props.data.reduce((sum, item) => sum + item.value, 0);

  const option = {
    title: {
      text: total,
      subtext: "总次数",
      left: "center",
      top: "35%",
      textStyle: {
        fontSize: 20,
        fontWeight: "bold",
        color: "#262626",
      },
      subtextStyle: {
        fontSize: 12,
        color: "#8C8C8C",
        padding: [5, 0, 0, 0],
      },
    },
    tooltip: {
      trigger: "item",
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "50%"],
        center: ["50%", "42%"],
        avoidLabelOverlap: false,
        startAngle: 90,
        itemStyle: {
          borderRadius: 2,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          position: "outer",
          alignTo: "edge",
          margin: 20,
          formatter: (params) => {
            return [
              `{name|${wrapText(params.name)}}`,
              `{value|${params.value}次 ${Math.round(
                total == 0 ? 0 : (params.value / total) * 100
              )}%}`,
            ].join("\n");
          },
          rich: {
            name: {
              fontSize: 12,
              color: "#262626",
              padding: [0, 0, 2, 0],
              width: 120,
            },
            value: {
              fontSize: 11,
              color: "#8C8C8C",
              padding: [2, 0, 0, 0],
            },
          },
        },
        labelLine: {
          show: true,
          length: 12,
          length2: 8,
          minTurnAngle: 120,
          lineStyle: {
            color: "#E5E5E5",
          },
        },
        labelLayout: function (params) {
          const isLeft = params.labelRect.x < chartRef.value.clientWidth / 2;
          const points = params.labelLinePoints || [];
          // 更新终点位置
          points[2][0] = isLeft
            ? params.labelRect.x
            : chartRef.value.clientWidth - params.labelRect.width;
          return {
            labelLinePoints: points,
            x: isLeft ? 0 : chartRef.value.clientWidth,
            align: isLeft ? "left" : "right",
          };
        },
        data: props.data
          .filter((v) => v.value > 0)
          .map((item) => ({
            value: item.value,
            name: item.name,
            itemStyle: {
              color: getColor(item.type),
            },
          })),
      },
    ],
  };

  chart.setOption(option);
}

function initChart() {
  if (!chartRef.value) {
    setTimeout(() => initChart(), 400);
    return;
  }
  chart = echarts.init(chartRef.value);
  updateChart();
}

function wrapText(str, len = 4) {
  if (!str) return "";
  return str.replace(new RegExp(`(.{${len}})`, "g"), "$1\n");
}

// 监听数据变化
watch(
  () => props.data,
  (v) => {
    console.log("circle data :", v);
    initChart();
    updateChart();
  },
  { deep: true }
);

// 使用防抖处理 resize
let resizeTimer = null;
const handleResize = () => {
  if (resizeTimer) clearTimeout(resizeTimer);
  resizeTimer = setTimeout(() => {
    chart?.resize();
  }, 100);
};

window.addEventListener("resize", handleResize);

onMounted(() => {
  setTimeout(() => {
    initChart();
    updateChart();
  }, 300);
});

onUnmounted(() => {
  if (resizeTimer) clearTimeout(resizeTimer);
  chart?.dispose();
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  position: relative;
}

.chart-content {
  width: 100%;
  height: 100%;
  max-width: 320px;
  min-height: 240px;
  position: relative;
  z-index: 1;
}

/* 在小屏幕上自适应 */
@media screen and (max-width: 320px) {
  .chart-content {
    max-width: 100%;
    min-height: 200px;
  }

  .chart-container {
    padding: 5px;
  }
}
</style>
